<?php
namespace backend\models;

use Yii;
use yii\base\Model;
use yii\base\Exception;
use common\models\CustomerOrder;
use common\models\OrderProduct;
use common\models\TransferUndertake;


class OrderLogic extends Model
{
    public $pid;
    public $pcode;
    public $transfer;
    public $undertake;
    public $user;
    public $init_form;
    public $customer;
    public $product;
    //public $number;
    public $purchase_time;
    public $check_time;
    public $method;
    public $purchase_user;
    public $relation;


	public function formName()
    {
        return '';
    }

	public function rules()
	{
		return [
            [['pid', 'pcode', 'transfer', 'undertake', 'user', 'init_form', 'customer', 'product', 'purchase_time', 'check_time', 'method', 'purchase_user', 'relation'], 'required'],
            ['barcode', 'safe']
		];
	}

    public function add()
    {
        $order = md5(uniqid().time());
        $customer_order = new CustomerOrder;
        $customer_order->order = $order;
        $customer_order->cid = $this->customer;
        $customer_order->sid = $this->user;
        $customer_order->status = CustomerOrder::ACTIVE_STATUS;
        if ($customer_order->save(false)) {
            $order_product = new OrderProduct;
            $order_product->oid = $order;
            $order_product->pid = $this->product;
            $order_product->purchase_time = strtotime($this->purchase_time);
            $order_product->check_address = $this->method;
            $order_product->check_time = strtotime($this->check_time);
            $order_product->purchase_user = $this->purchase_user;
            $order_product->relation = $this->relation;
            $order_product->status = OrderProduct::ACTIVE_STATUS;
            if ($order_product->save(false)) {
                $transfer_undertake = new TransferUndertake;
                $transfer_undertake->transfer = $this->transfer;
                $transfer_undertake->undertake = $this->undertake;
                $transfer_undertake->pcode = $this->pcode;
                $transfer_undertake->pid = $this->pid;
                $transfer_undertake->status = TransferUndertake::ACTIVE_STATUS;
                $transfer_undertake->oid = $order;
                if ($transfer_undertake->save(false)) {

                    return true;
                }
            }
        }

        return false;
    }

}    